const script = document.createElement('script');
script.src = chrome.runtime.getURL('apiManager.js');
(document.head || document.documentElement).appendChild(script);
script.onload = function () {
    script.remove();
};

var App = {
    // Assuming this.$session.remove is a mock function to demonstrate the cache clearing.
    $session: {
        remove: function (key) {
            return new Promise(function (resolve) {
                console.log("Removing cache for:", key);
                // Simulate cache removal with a timeout
                setTimeout(function () {
                    resolve(true);
                }, 500);
            });
        }
    },
    $refs: {
        message: {
            addMessage: function (type, msg) {
                var messageContainer = document.querySelector('.message-container');
                var messageDiv = document.createElement('div');
                messageDiv.className = 'message ' + type;
                messageDiv.innerText = msg;
                messageContainer.appendChild(messageDiv);

                // Optionally, auto-remove the message after a few seconds
                setTimeout(function () {
                    messageContainer.removeChild(messageDiv);
                }, 1500);
            }
        }
    },
    removeList: function () {
        var t = this;
        return (async function () {
            try {
                // 删除 'dataCollection' 键及其数据
                chrome.storage.local.remove('dataCollection', function () {
                    console.log('dataCollection has been removed from storage');
                });
                //表格清空
                clearAllStorageData();
                t.$refs.message.addMessage("success", "清除成功！");
            } catch (err) {
                console.error("Error clearing cache:", err);
                t.$refs.message.addMessage("error", "清除失败！"); // This says "Clearing failed!"
            }
        })();
    },
    tabAccount: function () {
        try {
            this.isShow = true; // Show some UI elements or initiate a process
            this.$session.remove("tt_user");
            this.tt_user = null;
            this.$refs.message.addMessage("success", "账号已切换!"); // Account switched successfully
        } catch (err) {
            console.error("Error during account switch:", err);
            this.$refs.message.addMessage("error", "账号切换失败!"); // Failed to switch account
        }
    },
    setConfig: function () {

    },
    showSet: async function () {
        try {
            this.isSetting = true; // Assuming this flag toggles some UI settings elements.

            let fetchedConfig = await this.$session.get("setConfig");
            // If fetchedConfig is not defined, use an empty object.
            fetchedConfig = fetchedConfig || {};

            Object.assign(this.setConfig, fetchedConfig);
            console.log(this.setConfig, "===");

        } catch (err) {
            console.error("Error during showSet:", err);
            this.$refs.message.addMessage("error", "Failed to show settings.");
        }
    }
};


/*******参数定义 ***/

const newData = {
    url: "",
    status: "未采集" //未采集0  采集中1  采集成功 2
};

const pageData = {
    url: "",
    sales: "",
    status: "未采集" //未采集0  采集中1  采集成功 2
};

//平台类型
const MallType = {
    PDD: 1,
    TB: 2,
    TM: 3,
    JD: 4,
    OWN: 5,
    GHPT: 6,
    HYJ: 7,
    ALBB: 8,
    LAZADA: 9,
    JX: 10,
    SHOPEE: 11,
    ALIEXPRESS: 12,
    CrossBorder: 13,
    HYJHW: 15,
    TOKOPEDIA: 16,
    BUKALAPAK: 17,
    DTSHARE: 20
};

const shopeeSites = {
    my: "https://my.xiapibuy.com",
    tw: "https://xiapi.xiapibuy.com",
    vn: "https://vn.xiapibuy.com",
    id: "https://id.xiapibuy.com",
    ph: "https://ph.xiapibuy.com",
    th: "https://th.xiapibuy.com",
    sg: "https://sg.xiapibuy.com",
    br: "https://br.xiapibuy.com",
    cn: "https://detail.1688.com"
};

const shopeeSitesAlter = {
    my: "https://shopee.com.my",
    tw: "https://shopee.tw",
    vn: "https://shopee.vn",
    id: "https://shopee.co.id",
    ph: "https://shopee.ph",
    th: "https://shopee.co.th",
    sg: "https://shopee.sg",
    br: "https://shopee.com.br",
    mx: "https://shopee.com.mx",
    co: "https://shopee.com.co",
    ck: "https://shopee.cl",
    pl: "https://shopee.pl",
    fr: "https://shopee.fr",
    es: "https://shopee.es"
};


/*******方法区全局  start***/
// content.js
function injectScript(file_path, tag) {
    console.log("injectScript 执行")
    var node = document.getElementsByTagName(tag)[0];
    var script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', file_path);
    node.appendChild(script);
}

//缓存清除
function clearAllStorageData() {
    const tableBody = document.querySelector('#data-table tbody');
    if (tableBody) {
        tableBody.innerHTML = ''; // 清空表格内容
    }
    const scheduleDiv = document.querySelector('.schedule');
    if (scheduleDiv) {
        scheduleDiv.textContent = `当前进度0/0`;
    } else {
        console.error('Schedule element not found!');
    }

    const loginDisplay = document.getElementById('loginShow');
    if (loginDisplay) {
        // Display the default message
        loginDisplay.innerHTML = '<span class="etailer-set">🔒</span> <span>请登录后操作</span>';
    }

    // 检查并清除sessionStorage中的isLoggedIn和username
    if (localStorage.getItem('isLoggedIn') !== null) {
        localStorage.removeItem('isLoggedIn');
    }
    if (localStorage.getItem('username') !== null) {
        localStorage.removeItem('username');
    }
    if (localStorage.getItem('userId') !== null) {
        localStorage.removeItem('userId');
    }

    // 清除所有本地存储数据
    chrome.storage.local.clear(function () {
        var error = chrome.runtime.lastError;
        if (error) {
            console.error(error);
        } else {
            console.log('所有本地存储数据已被清除');
            // 可以在这里添加其他的清理逻辑，比如更新UI
        }
    });

}

// 设置 IsCollectOpen 的值
function setIsCollectOpen(value) {
    chrome.storage.local.set({ isCollectOpen: value }, function () {
        console.log('Value is set to ' + value);
    });
}

// 获取 IsCollectOpen 的值
function getIsCollectOpen(callback) {
    chrome.storage.local.get(['isCollectOpen'], function (result) {
        callback(result.isCollectOpen);
    });
}

// 检查用户是否登录的函数
function checkIfLoggedIn() {
    // 尝试从 localStorage 获取登录状态
    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
    const username = localStorage.getItem('username');

    // 如果没有找到登录标记或标记为 false，则用户未登录
    if (!isLoggedIn) {
        // 这里可以添加更多的逻辑，例如重定向到登录页面或弹出登录窗口
        //未登录
        return false;
    } else {
        return true;
    }
}

//设置全局参数获取
function injectScriptToAccessGlobalVariable() {
    const script = document.createElement('script');
    script.textContent = `
        if (window.__INIT_DATA) {
            window.postMessage({ type: 'FROM_PAGE_1688', text: window.__INIT_DATA }, '*');
        }
    `;
    (document.head || document.documentElement).appendChild(script);
    script.remove();
}

// 定义一个函数用于添加class和div
// content.js
function addUshopClassAndDiv() {
    const pattern = /i\.\d+\.\d+/; // 匹配 'i' 后跟一串数字，一个点，再跟一串数字
    const links = document.querySelectorAll('a[data-sqe="link"], a[href]');
    // console.log("页面渲染")

    links.forEach(link => {
        // console.log(link.href + "++" + pattern.test(link.href))
        if (pattern.test(link.href) && !link.classList.contains('etailer-box')) {
            // 如果链接符合模式并且尚未增强，则增强链接
            enhanceLink(link);
        }
    });
}

//采集链接
function pageLinkToCache(newItem) {
    // 获取现有数据
    chrome.storage.local.get({ pageCollection: [] }, function (result) {
        const collection = result.pageCollection;

        // 确定新数据的ID
        const nextId = collection.length > 0 ? collection[collection.length - 1].id + 1 : 1;
        newItem.id = nextId; // 设置ID

        // 将新数据添加到数组中
        collection.push(newItem);

        // 将更新后的数据保存回缓存
        chrome.storage.local.set({ pageCollection: collection }, function () {
            console.log('New item added with id:', nextId);
        });
    });
}


//页面渲染
function enhanceLink(link) {
    // Add the 'etailer-box' class to the link
    link.classList.add('etailer-box');

    // Define the HTML string for the new content
    const newDivHtml = `
     <div class="dxm-link-next test" style="opacity: 0;">
       <div>采集到EtailerIQ</div>
     </div>
   `;

    // Insert the new HTML as the last child of the link
    link.insertAdjacentHTML('beforeend', newDivHtml);
    // 查找新添加的div，并为它添加点击事件监听器
    const newDiv = link.querySelector('.dxm-link-next');
    newDiv.addEventListener('click', function (event) {
        if (!checkIfLoggedIn()) {
            App.$refs.message.addMessage("warning", "请先登录!");
            return;
        }
        event.stopPropagation(); // 防止事件冒泡到链接本身
        event.preventDefault(); // 防止<a>标签的默认行为

        // 获取点击的div中的子div，并更改其文本内容和颜色
        const textDiv = newDiv.firstElementChild; // 或者 newDiv.children[0]
        if (textDiv) {
            textDiv.textContent = '采集中...';
            textDiv.style.color = '#49e37b'; // 设置文本颜色
        }
        collectData(link.href); // 调用 collectData 函数并传递商品链接
        if (textDiv) {
            textDiv.textContent = '采集完成';
            textDiv.style.color = '#49e37b'; // 设置文本颜色
        }
    });
}

//数据采集
function collectData(href) {
    // 这里应该是你获取数据和处理逻辑的代码
    console.log('采集数据的链接：', href);
    // 你可以在这里添加 AJAX 请求或者其他的逻辑来处理采集的数据
    window.open(href, '_blank'); // 使用 '_blank' 作为第二个参数打开新标签页
    // chrome.runtime.sendMessage({action: "openNewTab", url: href});
    setIsCollectOpen(true);
}

// 定义一个回调函数，用于当我们关注的元素出现在DOM中时执行
function waitForElements() {
    // 使用MutationObserver来等待元素添加
    const observer = new MutationObserver(function (mutations, me) {
        // 查询特定的元素
        if (document.querySelectorAll('a[data-sqe="link"]').length) {
            addUshopClassAndDiv(); // 当这些元素出现时，执行我们的函数
            // me.disconnect(); // 停止观察
            return;
        }
    });

    // 开始观察整个文档的变化
    observer.observe(document, {
        childList: true, // 子元素的变动
        subtree: true // 子树（即所有后代元素）的变动
    });
}

/*******方法区全局  end ***/



/******初始化方法 start */


// 初始化开始监听
waitForElements();


/******初始化方法 end */


document.addEventListener("DOMContentLoaded", function () {
    // 注入HTML到页面
    // 在content script中
    //参数定义区
    let collectBoxHTML = '';
    let selectedAccount = 'main'; // 'main' or 'sub'

    //判断是否登录过了
    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
    const username = localStorage.getItem('username');



    fetch(chrome.runtime.getURL('EtailerIQ.html'))
        .then(response => response.text())
        .then(async data => {
            collectBoxHTML = data;
            document.body.insertAdjacentHTML('beforeend', collectBoxHTML);

            //查询对象定义区 
            var overlayLogin = document.querySelector('.overlayLogin');

            var overlayCollect = document.querySelector('.overlayCollect');

            var overlayCollectAll = document.querySelector('.overlayCollectAll');

            // 支持拖拽
            const collectBox = document.querySelector('.collect-box');

            if (localStorage.getItem('pageRefreshed')) {
                // 执行页面刷新后需要进行的操作
                //店铺开始授权
                authMallTt();
                // 移除标记
                localStorage.removeItem('pageRefreshed');
            }
            //更新虾皮采集方式 兼容 add by hql20240105
            extractInitialState();

            function extractInitialState() {
                const scripts = document.querySelectorAll('script[type="text/mfe-initial-data"]');
                scripts.forEach(script => {
                    const dataModule = script.getAttribute('data-module');
                    if (dataModule) {
                        try {
                            const decodedModule = atob(dataModule); // 解码Base64
                            if (decodedModule.includes('productdetailspage')) { // 检查是否为所需的模块
                                const initialState = JSON.parse(script.textContent); // 解析initialState
                                console.log('找到InitialState:', initialState);
                                // 这里可以添加其他逻辑，如发送到后台或显示在UI中
                                if (initialState && initialState.initialState.item.items) {
                                    const items = initialState.initialState.item.items;
                                    // 检查items是否存在且为对象
                                    if (items && typeof items === 'object' && !Array.isArray(items)) {
                                        // 使用Object.entries()迭代对象的每个属性
                                        Object.entries(items).forEach(([key, item]) => {
                                            const response = createResponse(item);
                                            const link = window.location.href;
                                            // 确保是商品详情页
                                            if (!isProductDetailPage(link)) {
                                                return;
                                            }
                                            window.postMessage({ type: "FROM_PAGE", url: link, text: JSON.stringify(response) }, "*");
                                            console.log(response);
                                        }
                                        );
                                    } else {
                                        console.log('Items不存在或不是一个集合对象');
                                    }



                                }
                            }
                        } catch (error) {
                            console.error('解析InitialState时出错:', error);
                        }
                    }
                });
            }

            //返回值定义
            function createResponse(itemData) {
                return {
                    "bff_meta": null,
                    "error": null,
                    "error_msg": null,
                    "data": {
                        "item": itemData
                    }
                };
            }

            //初始化方法
            makeDraggable(collectBox);

            //支持拖动
            function makeDraggable(element) {
                let isDragging = false;
                let offsetX, offsetY;

                element.addEventListener('mousedown', function (e) {
                    isDragging = true;
                    offsetX = e.clientX - element.getBoundingClientRect().left;
                    offsetY = e.clientY - element.getBoundingClientRect().top;
                });

                document.addEventListener('mousemove', function (e) {
                    if (isDragging) {
                        element.style.left = (e.clientX - offsetX) + 'px';
                        element.style.top = (e.clientY - offsetY) + 'px';
                    }
                });

                document.addEventListener('mouseup', function () {
                    isDragging = false;
                });

                element.addEventListener('dragstart', function (e) {
                    e.preventDefault();
                });
            }


            //清除缓存功能
            document.getElementById('clearCacheBtn').addEventListener('click', function () {
                // 清除缓存点击事件
                App.removeList();
            });


            //账号登录
            document.getElementById('loginShow').addEventListener('click', function () {
                //关闭
                overlayLogin.classList.remove('hidden');
                //登录显示
                overlayLogin.classList.toggle('visible');
            });

            //导入采集链接
            document.getElementById('collectLink').addEventListener('click', function () {
                if (!checkIfLoggedIn()) {
                    App.$refs.message.addMessage("warning", "请先登录!");
                    return;
                }
                // 完成后隐藏模态对话框
                overlayCollect.classList.remove('hidden');
                //登录显示
                overlayCollect.classList.toggle('visible');
            });

            //导入采集链接
            document.getElementById('clearLink').addEventListener('click', function () {
                if (!checkIfLoggedIn()) {
                    App.$refs.message.addMessage("warning", "请先登录!");
                    return;
                }
                const tableBody = document.querySelector('#data-table tbody');
                if (tableBody) {
                    tableBody.innerHTML = ''; // 清空表格内容
                }
                const scheduleDiv = document.querySelector('.schedule');
                if (scheduleDiv) {
                    scheduleDiv.textContent = `当前进度0/0`;
                } else {
                    console.error('Schedule element not found!');
                }

                // 删除 'dataCollection' 键及其数据
                chrome.storage.local.remove('dataCollection', function () {
                    console.log('dataCollection has been removed from storage');
                });

            });

            //店铺批量授权
            // document.getElementById('authMall').addEventListener('click', function () {

            //     if (!checkIfLoggedIn()) {
            //         App.$refs.message.addMessage("warning", "请先登录!");
            //         return;
            //     }

            //     // 第一步
            //     // Part 1: 页面初次加载时执行
            //     if (!localStorage.getItem('pageRefreshed')) {
            //         // 模拟点击切换链接
            //         const switchLink = document.querySelector('.form-tip');
            //         if (switchLink) {
            //             switchLink.click();
            //             localStorage.setItem('pageRefreshed', 'true');  // 设置一个标记
            //         }
            //     }

            //     //店铺开始授权
            //     authMallTt();
            // });

            //店铺授权
            function authMallTt(username, pwd) {
                //第二步
                // 等待页面可能的刷新或更新
                setTimeout(() => {
                    // 获取下拉箭头元素并点击以展开选项
                    // 获取下拉箭头元素并点击以展开选项
                    const dropdownArrow = document.querySelector('.next-select-arrow');
                    if (dropdownArrow) {
                        dropdownArrow.click();

                        // 检查列表项是否出现，并尝试选择它
                        function checkAndSelectListItem() {
                            const listItem = document.querySelector('li.next-menu-item[role="menuitem"][value="ph"]');
                            if (listItem) {
                                listItem.click();
                                console.log('List item for Philippines selected');
                            } else {
                                console.log('Waiting for the list item to appear...');
                                setTimeout(checkAndSelectListItem, 500);  // 500毫秒后重试
                            }
                        }

                        // 首次调用函数
                        setTimeout(checkAndSelectListItem, 500);
                    } else {
                        console.log('Dropdown arrow not found');
                    }

                    //第三步
                    // 填充用户名和密码字段
                    const usernameField = document.querySelector('#fm-login-id');
                    const passwordField = document.querySelector('#fm-login-password');


                    if (usernameField && passwordField) {
                        usernameField.value = username;
                        passwordField.value = pwd;

                        // 创建一个新的'input'事件
                        const event = new Event('input', { bubbles: true, cancelable: true });

                        // 触发事件来模拟用户输入
                        usernameField.dispatchEvent(event);
                        passwordField.dispatchEvent(event);
                    }

                    setTimeout(() => {
                        if (passwordField) {
                            passwordField.value = pwd;  // 确认密码
                            const event2 = new Event('input', { bubbles: true, cancelable: true });
                            passwordField.dispatchEvent(event2);  // 确认密码字段也触发事件
                        }
                    }, 1500);  // 等待切换链接和其他元素加载完成

                }, 2000);  // 等待切换链接和其他元素加载完成

                //第四部
                const confirmPasswordField = document.querySelector('#fm-login-password'); // 假设这是确认密码的选择器
                setTimeout(() => {
                    if (confirmPasswordField) {
                        confirmPasswordField.value = pwd;  // 确认密码
                        const event = new Event('input', { bubbles: true, cancelable: true });
                        confirmPasswordField.dispatchEvent(event);  // 确认密码字段也触发事件
                    }
                }, 1000);  // 等待切换链接和其他元素加载完成

                //第五步
                setTimeout(() => {
                    // 获取提交按钮元素
                    const submitButton = document.querySelector('#fm-login-submit');

                    // 检查元素是否存在
                    if (submitButton) {
                        // 在模拟点击前添加一个随机延时，模仿人类在点击之前的犹豫或延迟
                        const humanLikeDelay = Math.random() * 2000; // 生成一个0到2000毫秒的随机延时
                        setTimeout(() => {
                            // 模拟点击提交按钮
                            submitButton.click();
                        }, humanLikeDelay);
                    } else {
                        console.log('Submit button not found');
                    }
                }, 3000);  // 从上一个动作完成后等待一段时间再执行
            }



            // 为采集按钮添加事件监听器
            document.querySelector('.zt-collect-begin').addEventListener('click', function () {
                // 获取用户输入的文本
                const userInput = document.querySelector('.my-input__inner.my-textarea.zk-link').value;
                const collectButton = this; // 或者直接使用 document.querySelector('.zt-collect-begin')


                //获取链接数组
                const linksArray = userInput.split('\n').filter(link => link.trim() !== '');
                // 禁用按钮防止重复点击
                collectButton.disabled = true;

                if (linksArray.length === 0) {
                    alert("请输入有效的链接！");
                    collectButton.disabled = false; // 重新启用按钮以允许用户再次尝试
                    return;
                }

                // 初始化链接状态为未采集
                const initialItems = linksArray.map(link => ({ url: link }));
                addToCache(initialItems);

                chrome.runtime.sendMessage({ action: "processLinks", links: linksArray });

                // 完成后隐藏模态对话框
                overlayCollect.classList.remove('visible');
                overlayCollect.classList.toggle('hidden');
            });

            chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
                if (request.action === "doBusinessOperation") {
                    App.$refs.message.addMessage("warning", "正在加载虾皮数据 请勿关闭窗口!");

                    // 这里获取请求中的链接
                    const link = request.link;
                    console.log("正在处理的链接: " + link);
                    new Promise((resolve, reject) => {
                        // App.$refs.message.addMessage("warning", "虾皮数据加载完毕!");
                        const ret = collectProductData(link); // 确保这个函数能处理链接参数
                        setTimeout(function () {
                            try {
                                App.$refs.message.addMessage("success", "虾皮数据 采集完成!");
                                console.log("采集结果 ===" + ret);
                                resolve({ action: "operationComplete" }); // 解决Promise
                            } catch (error) {
                                console.error("采集过程中出错：", error);
                                reject({ action: "operationFailed", error: error.message }); // 拒绝Promise
                            }
                        }, 1000);

                    }).then(response => {
                        sendResponse(response); // 发送响应
                    }).catch(errorResponse => {
                        sendResponse(errorResponse); // 发送错误响应
                    });

                    return true; // 保持消息通道打开
                }
            });



            // // 为采集按钮添加事件监听器
            // Assuming totalPages is the total number of pages in your data
            let currentPage = 1;
            // Assuming the 'Next Page' button has a class named 'shopee-icon-button--right'

            function delay(ms) {
                return new Promise(resolve => setTimeout(resolve, ms));
            }

            async function clickNextPageWithDelay() {
                return new Promise(async resolve => {
                    if (nextPageButton) {
                        nextPageButton.click();

                        // Use delay function to add a delay of 8000 milliseconds (8 seconds)
                        await delay(8000);

                        resolve();
                    } else {
                        resolve(); // Resolve immediately if no 'Next Page' button is found
                    }
                });
            }


            // Function to collect data from the current page
            function collectDataFromCurrentPage() {
                return new Promise(resolve => {
                    scrollToBottom(() => {
                        console.log("开始采集==");
                        fetchAndRenderCollectData();
                        filterSales();
                        window.scrollTo(0, 0); // Scroll back to the top
                        resolve();
                    });
                });
            }

            function getDeviceIdentifier() {
                const userId = localStorage.getItem('userId');
                return userId;
            }

            // Simple string hashing function
            function hashString(str) {
                let hash = 0;
                for (let i = 0; i < str.length; i++) {
                    const char = str.charCodeAt(i);
                    hash = (hash << 5) - hash + char;
                }
                return hash.toString();
            }


            const allowedDeviceIdentifier = "579e074a-d51f-4dda-aeeb-338047f7e30d";

            let totalPages = 1;


            document.querySelector('.zt-collect-page').addEventListener('click', async function () {
                // Clear table content only if it's the first page
                if (currentPage === 1) {
                    idCounter = 1;
                    const tableBody = document.querySelector('#data-table-page tbody');
                    if (tableBody) {
                        tableBody.innerHTML = ''; // Clear table content on the first page
                    }
                }

                const currentDeviceIdentifier = getDeviceIdentifier(); // Implement a function to retrieve the device identifier


                let openChannel = false;
                isCollectOver = false;
                firstCollectedData = null;

                if (currentDeviceIdentifier !== allowedDeviceIdentifier) {
                    App.$refs.message.addMessage("warning", "sorry 权限限制，只能采集当前页!");
                } else {
                    openChannel = true
                    App.$refs.message.addMessage("success", "支持采集多页!");
                    totalPages = 20;
                }


                // Assuming the 'totalPages' variable is defined
                for (let currentPage = 1; currentPage <= totalPages; currentPage++) {
                    await collectDataFromCurrentPage();
                    App.$refs.message.addMessage("success", "当前第" + currentPage + "页采集完成!");


                    const nextPageButton = document.querySelector('.shopee-icon-button--right');


                    // const over = document.querySelector('.shopee-icon-button--disabled');
                    if (isCollectOver) {
                        App.$refs.message.addMessage("success", "最后一页了,采集结束");
                        return;
                    }


                    if (nextPageButton && openChannel) {
                        nextPageButton.click();

                        App.$refs.message.addMessage("warning", "下一页跳转中，请稍等..");

                        await new Promise(resolve => setTimeout(resolve, 8000));
                        App.$refs.message.addMessage("warning", "下一页采集中");
                    }

                }


            });


            // 导入
            document.querySelector('.zt-import-page').addEventListener('click', function () {
                // 判断列表数据是否为空
                const links = document.querySelectorAll(".zk-collect-link");
                if (links.length == 0) {
                    return;
                }

                // 创建一个数组来存储所有的链接
                let urls = [];

                // 遍历所有链接，并添加到数组中
                links.forEach(link => {
                    if (link.offsetWidth > 0 || link.offsetHeight > 0) {
                        let url = link.innerHTML.trim(); // 去除字符串两端的空白
                        // console.log("url: " + url);
                        urls.push(url);
                    }

                });

                // 将所有链接用换行符连接
                let allLinks = urls.join('\n');

                overlayCollectAll.classList.remove('visible');
                //关闭
                overlayCollectAll.classList.toggle('hidden');

                // 输出所有链接
                // console.log("所有链接:\n" + allLinks);
                // 完成后隐藏模态对话框
                overlayCollect.classList.remove('hidden');
                overlayCollect.classList.toggle('visible');
                // 将链接字符串赋值给文本域
                const textarea = document.querySelector('.my-input__inner.my-textarea.zk-link');
                if (textarea) {
                    textarea.value = allLinks;
                } else {
                    console.error('Textarea element not found!');
                }
            });

            // 为采集按钮添加事件监听器
            document.querySelector('.zt-dataCopy').addEventListener('click', function () {
                copyTableContent();
            });

            // 为采集按钮添加事件监听器
            document.querySelector('.zt-filterSales').addEventListener('click', function () {
                filterSales();
            });

            function filterSales() {
                var salesThreshold = document.getElementById('sales-filter').value;
                var rows = document.querySelectorAll('#data-table-page tbody tr');

                rows.forEach(row => {
                    var sales = parseInt(row.cells[2].textContent, 10);
                    row.style.display = sales >= salesThreshold ? '' : 'none';
                });
            }

            //复制
            function copyTableContent() {

                const table = document.getElementById('data-body-page');
                var salesThreshold = document.getElementById('sales-filter').value;
                let textToCopy = '';

                for (const row of table.rows) {
                    let rowData = [];

                    // 假设数量在每行的第N个单元格（从0开始计数）
                    const quantity = parseInt(row.cells[2].textContent, 10);

                    // 只处理数量符合条件的行
                    if (quantity >= salesThreshold) {
                        for (const cell of row.cells) {
                            rowData.push(cell.textContent.trim());
                        }

                        textToCopy += rowData.join('\t') + '\n'; // 使用制表符分隔每个单元格的内容
                    }
                }

                try {
                    navigator.clipboard.writeText(textToCopy);
                    App.$refs.message.addMessage("success", "表格内容已复制到剪贴板!");
                } catch (err) {
                    App.$refs.message.addMessage("error", "复制失败!");
                    console.error('复制失败', err);
                }
            }



            //页面滚动
            function scrollToBottom(callback) {
                const distance = 100; // 每次滚动的距离
                const delay = 100; // 每次滚动的延迟

                function isScrollAtBottom() {
                    const scrolled = window.scrollY + window.innerHeight; // 当前滚动的高度
                    const totalHeight = document.documentElement.scrollHeight; // 总高度
                    return scrolled >= totalHeight;
                }

                const timer = setInterval(() => {
                    if (isScrollAtBottom()) {
                        clearInterval(timer);
                        if (callback) callback(); // 当滚动到底部时，执行回调函数
                        return;
                    }

                    window.scrollBy(0, distance); // 向下滚动
                }, delay);
            }

            let idCounter = 1; // 初始化ID计数器


            //搜集页面数据
            function collectPageData() {
                const baseHref = window.location.origin; // 获取当前页面的基础URL
                // const links = document.querySelectorAll('a[data-sqe="link"]');
                const links = document.querySelectorAll('a[data-sqe="link"], a[href]');
                //虾皮的
                const pattern = /i\.\d+\.\d+/; // 匹配 'i' 后跟一串数字，一个点，再跟一串数字
                // 1688
                const pattern2 = /https:\/\/dj\.1688\.com\/ci_bb\?/;

                const pattern1688 = /\/\/detail\.1688\.com\/offer\/\d+\.html/;


                const collectedData = Array.from(links).map(link => {
                    if (pattern.test(link.href) || pattern2.test(link.href) || pattern1688.test(link.href)) {
                        const relativeHref = link.getAttribute('href');
                        const href = new URL(relativeHref, baseHref).href;
                        const salesInfo = Array.from(link.querySelectorAll('div')).find(div => div.innerText.includes('已售出') || div.innerText.includes('sold') || div.innerText.includes('售') || div.innerText.includes('销') || div.innerText.includes('成交'));
                        let sales = 0;
                        if (salesInfo) {
                            const salesInfoText = salesInfo ? salesInfo.innerText : "";
                            console.log(salesInfoText)

                            sales = extractSales(salesInfoText);
                            console.log(sales)

                        }

                        const pageData = { // 创建新对象
                            id: idCounter++, // 自增ID
                            url: href,
                            sales: sales
                        };
                        return pageData;
                    }
                });

                return collectedData.filter(data => data); // 过滤掉不符合模式的数据
            }

            //销量数据提取
            function extractSales(salesInfoText) {

                let sales = 0;
                const salesMatch = salesInfoText.match(/销(\d+(\.\d+)?)\+?件/);
                if (salesMatch) {
                    sales = parseFloat(salesMatch[1]);
                    return sales;
                } else {
                    // 匹配 "成交12.8万+元" 格式
                    const salesAmountMatch = salesInfoText.match(/成交(\d+(\.\d+)?)万?\+?元/);
                    if (salesAmountMatch) {
                        sales = parseFloat(salesAmountMatch[1]);
                        if (salesInfoText.includes("万")) {
                            sales *= 10000;
                            return sales;
                        }
                    }
                }

                // 匹配 "数字 sold" 的模式
                const match = salesInfoText.match(/(\d+) sold/i);
                if (match) {
                    sales = parseInt(match[1], 10);
                    return sales;
                }

                // 匹配 "数字 sold" 的模式
                const matchXiapi = salesInfoText.match(/(\d+) 售/i);
                if (matchXiapi) {
                    sales = parseInt(match[1], 10);
                    //    return sales;
                }

                // 处理包含"万"的情况
                const salesMatchWan = salesInfoText.match(/已售出 ([\d,.]+)萬/);
                if (salesMatchWan) {
                    sales = parseFloat(salesMatchWan[1].replace(/,/g, '')) * 10000;
                } else {
                    // 处理包含"k"或"K"的情况
                    const salesMatchK = salesInfoText.match(/(\d+(\.\d+)?)k/i);
                    if (salesMatchK) {
                        sales = parseFloat(salesMatchK[1]) * 1000;
                    } else {
                        // 处理普通数字格式（可能包含逗号）
                        const salesMatch = salesInfoText.match(/已售出 ([\d,]+)|sold (\d+)/i);
                        if (salesMatch) {
                            sales = parseInt(salesMatch[1]?.replace(/,/g, '') || salesMatch[2]?.replace(/,/g, ''), 10);
                        }
                    }
                }

                return sales;
            }

            let firstCollectedData = null;
            let isCollectOver = false;


            //获取商品列表的数据
            function fetchAndRenderCollectData() {
                const pageCollection = collectPageData();


                // 检查是否有重复数据
                if (firstCollectedData !== null && pageCollection.length > 0) {
                    if (firstCollectedData.url === pageCollection[0].url) {
                        console.log('停止采集，发现重复数据');
                        isCollectOver = true
                        // 返回空数组或其他表示停止采集的标志
                        return [];
                    }
                    firstCollectedData = pageCollection[0];
                }

                // 如果是第一次采集，存储第一条数据
                if (firstCollectedData === null && pageCollection.length > 0) {
                    firstCollectedData = pageCollection[0];
                }


                if (pageCollection.length > 0) {
                    console.log('Retrieved data collection:', pageCollection);
                    // 如果存在数据，则渲染表格
                    insertPageIntoTable(pageCollection);
                } else {
                    // 如果没有数据，则在控制台中记录消息
                    console.log('No data found in pageCollection');
                }

            }

            // 将数据集合组装成表格行并插入到表格中的函数
            function insertPageIntoTable(dataCollection) {
                // 获取表格的tbody元素
                const tableBody = document.querySelector('#data-table-page tbody');

                if (tableBody) {
                    // Check if there is existing content in the tbody
                    const existingContent = tableBody.innerHTML;

                    // Generate HTML for new rows
                    const tableRows = dataCollection.map(createListRow).join('');

                    // Append the new rows to the existing content
                    tableBody.innerHTML = existingContent + tableRows;
                } else {
                    // 如果找不到tbody元素，则抛出错误
                    console.error('Table body not found!');
                }
            }


            function createListRow(data) {
                // 注意: 这里我们添加了一个data-id属性到删除按钮，这样我们就可以知道要删除哪个条目
                return `
                <tr data-id="${data.id}">
                    <td class="w-6">${data.id}</td>
                    <td class="show-overflow" style="width: 220px;text-align: center;">
                        <div  class="zk-collect-link">${data.url}</div>
                    </td>
                    <td style="width: 80px;text-align: center;">
                       <div>${data.sales}</div>
                    </td>
                </tr>
                `;
            }



            //功能关闭
            document.querySelector('.close-btn-login').addEventListener('click', function () {
                // Show the overlay by removing the 'hidden' class
                overlayLogin.classList.remove('visible');
                //关闭
                overlayLogin.classList.toggle('hidden');
            });

            //功能关闭
            document.querySelector('.close-btn-collect').addEventListener('click', function () {
                // Show the overlay by removing the 'hidden' class
                overlayCollect.classList.remove('visible');
                //关闭
                overlayCollect.classList.toggle('hidden');
            });
            //功能关闭
            document.querySelector('.close-btn-collectAll').addEventListener('click', function () {
                // Show the overlay by removing the 'hidden' class
                overlayCollectAll.classList.remove('visible');
                //关闭
                overlayCollectAll.classList.toggle('hidden');
            });


            var toggleButton = document.getElementById('toggleButton');

            const mainAccountLabel = document.getElementById('mainAccountLabel');
            const subAccountLabel = document.getElementById('subAccountLabel');
            const radioButtons = document.querySelectorAll('.custom-radio-wrapper');


            toggleButton.addEventListener('click', function () {
                // Get the button's current text content
                const buttonText = toggleButton.querySelector('span').textContent;
                const scheduleBox = document.querySelector('.schedule-box-zk');

                // Check the current text and toggle it
                if (buttonText === '收起') {
                    scheduleBox.style.display = 'none'; // Show the content
                    toggleButton.querySelector('span').textContent = '查看当前进度';
                } else {
                    scheduleBox.style.display = 'block'; // Hide the content
                    toggleButton.querySelector('span').textContent = '收起';
                }


            });


            //表格渲染
            function createTableRow(data) {
                // 根据状态确定要应用的样式类
                const statusClass = data.status === '采集成功' ? 'text-green' : data.status === '采集失败' ? 'text-red' : '';

                return `
                <tr data-id="${data.id}">
                    <td class="w-6">${data.id}</td>
                    <td class="show-overflow" style="width: 160px;">
                        <div>${data.url}</div>
                    </td>
                    <td style="width: 80px;">
                        <div class="${statusClass}">${data.status}</div>
                    </td>
                    <td style="width: 80px;">
                        <div><span class="etailer-del" data-id="${data.id}">删除</span></div>
                    </td>
                </tr>
                `;
            }


            // 删除数据条目的函数
            function deleteDataEntry(id) {
                chrome.storage.local.get({ dataCollection: [] }, function (result) {
                    const newDataCollection = result.dataCollection.filter(item => item.id !== id);
                    chrome.storage.local.set({ dataCollection: newDataCollection }, function () {
                        console.log(`Data entry with id ${id} deleted.`);
                        // 重新渲染表格
                        insertDataIntoTable(newDataCollection);
                    });
                });
            }

            // 函数来添加事件监听器到所有的删除按钮
            function addDeleteEventListeners() {
                document.querySelectorAll('.etailer-del').forEach(button => {
                    button.addEventListener('click', function () {
                        const idToDelete = parseInt(button.getAttribute('data-id'));
                        deleteDataEntry(idToDelete);
                    });
                });
            }

            function updateLinkStatus(key, status) {
                chrome.storage.local.get({ dataCollection: [] }, function (result) {
                    let collection = result.dataCollection;
                    let itemIndex = collection.findIndex(item => item.key === key);

                    if (itemIndex !== -1) {
                        collection[itemIndex].status = status;

                        chrome.storage.local.set({ dataCollection: collection }, function () {
                            if (chrome.runtime.lastError) {
                                console.error('Error updating storage:', chrome.runtime.lastError.message);
                                return;
                            }
                            console.log(`Item with key ${key} updated to status: ${status}`);
                            fetchAndRenderData();
                        });
                    } else {
                        console.error('Item not found for key:', key);
                    }
                });
            }


            //添加数据到集合中
            function addToCache(newItems) {
                if (!newItems.length) {
                    return;
                }
                chrome.storage.local.get({ dataCollection: [] }, function (result) {
                    let collection = result.dataCollection;

                    newItems.forEach(newItem => {
                        if (newItem.url === '') {
                            return;
                        }

                        // 检查URL是否已存在于集合中
                        const existingItem = collection.find(item => item.key === newItem.key || item.url === newItem.url);
                        if (existingItem) {
                            console.log(`Item with URL ${newItem.url} already exists in the collection.`);
                            return; // 如果URL已存在，则跳过添加这个新项目
                        }
                        const platform = getPlatform(newItem.url);

                        let key = extractKey(platform, newItem.url);

                        const nextId = collection.length > 0 ? collection[collection.length - 1].id + 1 : 1;
                        newItem.id = nextId; // 设置ID
                        newItem.key = key; // 设置ID
                        newItem.status = newItem?.status || '待采集';
                        collection.push(newItem);
                    });

                    chrome.storage.local.set({ dataCollection: collection }, function () {
                        if (chrome.runtime.lastError) {
                            console.error('Error saving to storage:', chrome.runtime.lastError.message);
                            return;
                        }
                        console.log('Items added:', newItems.length);
                        fetchAndRenderData();
                    });
                });
            }


            // 调用这个函数来初始化事件监听器
            addDeleteEventListeners();

            // 将数据集合组装成表格行并插入到表格中的函数
            function insertDataIntoTable(dataCollection) {
                const tableRows = dataCollection.map(createTableRow).join('');
                // 获取表格的tbody元素
                const tableBody = document.querySelector('#data-table tbody');
                if (tableBody) {
                    // 将生成的HTML字符串设置为tbody的内容
                    tableBody.innerHTML = tableRows;
                } else {
                    // 如果找不到tbody元素，则抛出错误
                    console.error('Table body not found!');
                }
                // 添加事件监听器到所有新创建的删除按钮
                addDeleteEventListeners();
                //更新进度
                updateProgress();
            }

            function updateSelectedAccount() {
                if (selectedAccount === 'main') {
                    radioButtons[0].checked = true;
                    radioButtons[1].checked = false;
                    mainAccountLabel.classList.add('checked');
                    subAccountLabel.classList.remove('checked');
                } else {
                    radioButtons[0].checked = false;
                    radioButtons[1].checked = true;
                    mainAccountLabel.classList.remove('checked');
                    subAccountLabel.classList.add('checked');
                }
            }

            function fetchAndRenderData() {
                chrome.storage.local.get({ dataCollection: [] }, function (result) {
                    if (result.dataCollection.length > 0) {
                        console.log('Retrieved data collection:', result.dataCollection);
                        // 如果存在数据，则渲染表格
                        insertDataIntoTable(result.dataCollection);
                    } else {
                        // 如果没有数据，则在控制台中记录消息
                        console.log('No data found in dataCollection');
                    }
                });
            }

            // Click event listener for the "主账号" label
            mainAccountLabel.addEventListener('click', function () {
                selectedAccount = 'main';
                updateSelectedAccount();
            });

            // Click event listener for the "子账号" label
            subAccountLabel.addEventListener('click', function () {
                selectedAccount = 'sub';
                updateSelectedAccount();
            });

            //content.js 
            // 点击事件监听器 
            document.getElementById('collectList').addEventListener('click', function () {
                if (!checkIfLoggedIn()) {
                    App.$refs.message.addMessage("warning", "请先登录!");
                    return;
                }
                const link = window.location.href;
                // 确保是商品详情页
                if (!isProductDetailPage(link)) {
                    App.$refs.message.addMessage("warning", "请到商品详情页采集!");
                    return false;
                }
                addToCache([{ url: link, status: '未采集' }]);
                //商品采集 
                collectProductData();

            });

            document.getElementById('collectAllList').addEventListener('click', function () {
                if (!checkIfLoggedIn()) {
                    App.$refs.message.addMessage("warning", "请先登录!");
                    return;
                }

                // 完成后隐藏模态对话框
                overlayCollectAll.classList.remove('hidden');
                //登录显示
                overlayCollectAll.classList.toggle('visible');
            });

            //商品采集
            function collectProductData(link) {
                // 确保链接有效，否则使用当前页面的 URL
                link = link || window.location.href;
                console.log("当前采集链接: " + link);
                // 确保是商品详情页
                if (!isProductDetailPage(link)) {
                    App.$refs.message.addMessage("warning", "请到商品详情页采集!");
                    return false;
                }

                const platform = getPlatform(link);
                console.log("platform: " + platform);

                const code = getCountryCodeFromUrl(window.location.origin);
                console.log("code: " + code);

                let key = extractKey(platform, link);
                console.log("key: " + key);

                const userId = localStorage.getItem('userId');
                //重试机制
                // checkKeyAndGetData(key);

                // 异步获取存储的数据
                chrome.storage.local.get([key], function (result) {
                    const retdData = result[key];
                    if (!retdData) {
                        // alert("在缓存中找不到key")
                        console.log("在缓存中找不到key: ", key);
                        // 处理找不到数据的情况
                        updateLinkStatus(key, '采集失败');
                        return;
                    }


                    let responseData = JSON.parse(retdData);
                    console.log("responseData result:", responseData.data);

                    // 删除这个键的数据
                    chrome.storage.local.remove([key], function () {
                        if (chrome.runtime.lastError) {
                            console.error(`Error removing key ${key}: ${chrome.runtime.lastError.message}`);
                        } else {
                            console.log(`Data for key ${key} has been removed.`);
                        }
                    });
                    let coll_key = '';

                    if (platform == MallType.SHOPEE) {
                        coll_key = key.split('_')[1];
                    }

                    // 检查 responseData 是否包含 error 字段或数据不匹配
                    if (responseData.error || responseData.data.item.item_id != coll_key) {
                        console.error('采集错误或数据不匹配');
                        updateLinkStatus(key, '采集重复');
                        return;
                    }

                    updateLinkStatus(key, '采集成功');

                    // 发送数据
                    chrome.runtime.sendMessage({
                        action: "uploadData",
                        data: retdData,
                        platform: platform,
                        userLanguage: document.documentElement.lang,
                        key: coll_key,
                        code: code,
                        userId: userId,
                        ori_url: link
                    }, function (response) {
                        console.log("uploadData result:", response.code, response.msg);
                    });


                });
            }



            function checkKeyAndGetData(key) {
                const retryInterval = 1000; // 重试间隔时间，例如1000毫秒
                const maxRetries = 3; // 最大重试次数
                let attempt = 0; // 当前尝试次数

                const checkKeyAndGetData = () => {
                    chrome.storage.local.get([key], function (result) {
                        if (result[key] === undefined && attempt < maxRetries) {
                            // key 不存在，且尚未达到最大重试次数
                            console.log(`Key ${key} not found, retrying in ${retryInterval}ms...`);
                            setTimeout(checkKeyAndGetData, retryInterval); // 延时后再次尝试
                            attempt++;
                        } else if (result[key] !== undefined) {
                            // 找到了 key，处理数据
                            console.log("Data found for key:", key);
                            // ... 处理数据的代码 ...
                        } else {
                            // 重试次数耗尽，key 仍未找到
                            console.log(`Failed to find key ${key} after ${maxRetries} attempts.`);
                        }
                    });
                };
                checkKeyAndGetData(); // 开始执行数据检查和获取

            }




            //获取国家编码
            function getCountryCodeFromUrl(url) {
                //虾皮
                for (const countryCode in shopeeSites) {
                    if (url.includes(shopeeSites[countryCode])) {
                        return countryCode; // 返回匹配到的国家/地区编码
                    }
                }

                for (const countryCode in shopeeSitesAlter) {
                    if (url.includes(shopeeSitesAlter[countryCode])) {
                        return countryCode; // 返回匹配到的国家/地区编码
                    }
                }

                return null; // 如果没有匹配项，返回null
            }



            //根据链接获取 shopId 和 itemId 的部分  虾皮 1688
            function extractKey(platform, urlString) {
                if (MallType.ALBB == platform) {
                    return extractProductId(urlString);
                }
                // 使用正则表达式匹配包含 shopId 和 itemId 的部分
                const match = urlString.match(/i\.(\d+)\.(\d+)/);

                if (match) {
                    // 提取 shopId 和 itemId
                    const shopId = match[1];
                    const itemId = match[2];

                    // 组合成 key
                    const key = shopId + "_" + itemId;

                    // 返回对象
                    return key;
                } else {
                    // 如果匹配不成功，返回 null
                    return null;
                }
            }

            //1688
            function extractProductId(url) {
                const pattern = /detail\.1688\.com\/offer\/(\d+)\.html/;
                const match = url.match(pattern);
                if (match && match[1]) {
                    return match[1]; // This is the product ID
                } else {
                    return null; // No product ID found in the URL
                }
            }

            //collectMall
            document.getElementById('collectMall').addEventListener('click', function () {
                if (!checkIfLoggedIn()) {
                    App.$refs.message.addMessage("warning", "请先登录!");
                    return;
                }
                // Get the current page's URL
                // console.log("开始采集链接商品...");
                App.$refs.message.addMessage("warning", "开发中!");

            });

            // Wait for the DOM to load
            const loginButton = document.querySelector('.zt-button.zt-button-primary');


            // Event listener for login button
            loginButton.addEventListener('click', function () {
                // Get the user input
                const username = document.querySelector('.my-input input[type="text"]').value;
                const password = document.querySelector('.my-input input[type="password"]').value;
                const radioInput = document.querySelector('input[name="radio-group"]:checked');
                const accountType = radioInput ? radioInput.value : '1'; // or some default value

                // Here you would typically validate the inputs and then send them to your server
                if (username && password) {
                    // Example: Send data to your server for login
                    loginUser(username, password, accountType);
                } else {
                    // Inform the user that they need to enter both username and password
                    console.error('Please enter both username and password');
                }
            });


            window.addEventListener("message", (event) => {
                if (event.source == window && event.data.type && event.data.type == "FROM_PAGE") {
                    //https://ph.xiapibuy.com/api/v4/pdp/hot_sales/get?item_id=21862237629&limit=8&offset=0&shop_id=182560314
                    //https://xiapi.xiapibuy.com/api/v4/pdp/get_pc?shop_id=852160357&item_id=22269751332 i.852160357.22269751332
                    // 使用 URL 构造函数解析 URL
                    try {
                        const url = new URL(event.data.url);

                        // 获取 shop_id 和 item_id 的值
                        let shopId = url.searchParams.get('shop_id');
                        let itemId = url.searchParams.get('item_id');

                        const match = event.data.url.match(/i\.(\d+)\.(\d+)/);

                        if (match && !itemId) {
                            // 提取 shopId 和 itemId
                            shopId = match[1];
                            itemId = match[2];
                        }

                        // const key = `${shopId}_${itemId}`;
                        let key = shopId + "_" + itemId;

                        const valueToStore = event.data.text;


                        let responseData = JSON.parse(valueToStore);

                        // //判断采集链接是否能匹配的上数据 
                        if (responseData.data.item.item_id == itemId) {
                            chrome.storage.local.set({ [key]: valueToStore }, function () {
                                console.log('上传的数据已保存到存储。Key:', key);
                            })
                            //发送采集完成请求
                            chrome.runtime.sendMessage({
                                action: "collectComplete",
                                key: key, // 这里的 key 需要根据实际情况来设置
                                status: true // 假设数据处理成功
                            }, function (response) {
                                console.log("Background script response:", response);
                            });
                        } else {
                            console.log('Upload data failed');
                        }

                        //判断是否开启采集
                        getIsCollectOpen(function (value) {
                            if (value) {
                                //采集数据
                                collectProductData();
                                //重置标记位
                                setIsCollectOpen(false);
                            }
                        });
                    } catch (parseError) {
                        console.error('解析响应数据时出错:', parseError);
                        return; // 中断执行
                    }
                } else if (event.source == window && event.data.type && event.data.type == "FROM_PAGE_1688") {
                    //https://detail.1688.com/offer/680767719527.html?spm=a2638t.b_78128457.reofferlist.1.3836436caTmSoi&cosite=-&ilike_session=c0e9360944c34ad09021d1253d588d00&tracelog=p4p&_p_isad=1&clickid=c0e9360944c34ad09021d1253d588d00&sessionid=b72948fbfb5ea7955ba52a2bf1182bd9
                    console.log('Received data:', event.data.text);
                    const url = window.location.href;
                    const key = extractProductId(url);
                    if (key != null && event.data.text != null) {
                        const valueToStore = event.data.text;
                        const value = {
                            globalData: valueToStore.globalData,
                            data: valueToStore.data,
                            desc: ''
                        }
                        const stringifiedValue = JSON.stringify(value);

                        chrome.storage.local.set({ key: stringifiedValue }, function () {
                            // 使用计算属性名来设置对象的键
                            console.log('Upload data saved to storage with key:', key + stringifiedValue);
                        });
                    } else {
                        console.log('链接校验失败');
                    }
                }

            });


            // 1688参数获取 然后在需要的地方调用这个函数
            injectScriptToAccessGlobalVariable();

            //用户登录
            function loginUser(username, password, accountType) {
                console.log('Logging in with:', username, password, accountType);

                let loginSuccessful = false;

                chrome.runtime.sendMessage({
                    action: "login",
                    username: username,
                    password: password,
                    accountType: accountType
                }, function (response) {
                    if (response.data.code === 200) {
                        console.log("登录成功:", response.data);
                        // 登录成功
                        App.$refs.message.addMessage("success", "登录成功!");
                        localStorage.setItem('isLoggedIn', true);
                        localStorage.setItem('username', username);

                        localStorage.setItem('userId', response.data.data.id);
                        loginSuccessful = true;
                        // 处理登录成功的逻辑
                        // 关闭登录模态框
                        overlayLogin.classList.remove('visible');
                        overlayLogin.classList.add('hidden');
                        updateLoginDisplay(username);
                    } else {
                        console.error("登录失败:", response.message);
                        // 处理登录失败的逻辑
                        // 如果登录不成功，则显示错误消息
                        if (!loginSuccessful) {
                            App.$refs.message.addMessage("warning", "用户名或密码错误!");
                            localStorage.setItem('isLoggedIn', false);
                        }
                    }
                });

            }


            //更新当前用户状态
            function updateLoginDisplay(username) {
                const loginDisplay = document.getElementById('loginShow');
                if (username && loginDisplay) {
                    // Update the HTML to show the logged-in user
                    loginDisplay.innerHTML = `<span class="etailer-set">🔓</span> <span>欢迎，${username}</span>`;
                } else {
                    // Display the default message
                    loginDisplay.innerHTML = '<span class="etailer-set">🔒</span> <span>请登录后操作</span>';
                }
            }

            if (isLoggedIn && username) {
                updateLoginDisplay(username);
            }


            //商品检查规则
            function isProductDetailPage(url) {
                const decodedUrl = decodeURIComponent(url);

                // 正则表达式检查 'i.' 后面跟着一系列数字，并可能包含一个或多个点号分隔的数字序列
                // const productPagePattern = /\/i\.\d+(\.\d+)?/;
                const patternxiapi = /-i\.\d+(\.\d+)?/;

                const pattern1688 = /detail\.1688\.com\/offer\/(\d+)\.html/;

                return patternxiapi.test(decodedUrl) || pattern1688.test(decodedUrl);
            }

            //
            function getPlatform(url) {
                const decodedUrl = decodeURIComponent(url);
                // const productPagePattern = /\/i\.\d+(\.\d+)?/;
                const patternxiapi = /-i\.\d+(\.\d+)?/;

                const pattern1688 = /detail\.1688\.com\/offer\/(\d+)\.html/;
                if (patternxiapi.test(decodedUrl)) {
                    platform = MallType.SHOPEE;
                } else if (pattern1688.test(decodedUrl)) {
                    platform = MallType.ALBB;
                } else {
                    platform = MallType.SHOPEE;
                }

                return platform;
            }

            //更新表格进度
            function updateProgress() {
                const tableRows = document.querySelectorAll('table tbody tr');
                const total = tableRows.length;
                let completed = 0;

                tableRows.forEach(row => {
                    const statusCell = row.querySelector('td:nth-child(3) div'); // Assuming status is in the 3rd column
                    if (statusCell && statusCell.textContent.trim() === '采集成功') {
                        completed++;
                    }
                });

                // Update the progress display
                const scheduleDiv = document.querySelector('.schedule');
                if (scheduleDiv) {
                    scheduleDiv.textContent = `当前进度${completed}/${total}`;
                } else {
                    console.error('Schedule element not found!');
                }
            }

            // Call this function to update the progress whenever needed
            updateProgress();
            //初始化获取表格数据
            fetchAndRenderData();


        })
        .catch(error => console.error('Error loading EtailerIQ.html:', error));

    injectScript(chrome.runtime.getURL('injected.js'), 'body');

});




